import sys
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QIcon

from .Ui_download_config import Ui_DownloadConfig
from ..setting import SETTINGS, SETTING_FILENAME
from ..utility import save_json


class DownloadConfig(QDialog, Ui_DownloadConfig):
    def __init__(self):
        super(DownloadConfig, self).__init__()
        self.setupUi(self)

        self.initUi()

    def initUi(self):
        '''初始化界面'''
        # 设置窗口的图标
        self.setWindowIcon(QIcon(r'images\YuLan.png'))

        if SETTINGS["DataSource"] == 2:
            self.rbSource2.setChecked(True)
        elif SETTINGS["DataSource"] == 3:
            self.rbSource3.setChecked(True)
        if SETTINGS["EveryTime"] != 0:
            self.chkEveryTime.setChecked(True)

    def SaveSetting(self):
        if self.rbSource2.isChecked():
            SETTINGS["DataSource"] = 2
        elif self.rbSource3.isChecked():
            SETTINGS["DataSource"] = 3
        else:
            SETTINGS["DataSource"] = 1
        if self.chkEveryTime.isChecked():
            SETTINGS["EveryTime"] = 1
        else:
            SETTINGS["EveryTime"] = 0
        save_json(SETTING_FILENAME, SETTINGS)

    @pyqtSlot()
    def on_btnOK_clicked(self):
        '''确认'''
        self.SaveSetting()
        self.accept()

    @pyqtSlot()
    def on_btnCancel_clicked(self):
        '''取消'''
        self.reject()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = DownloadConfig()
    ui.show()
    sys.exit(app.exec_())
